package com.history.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.history.common.Logit;
import com.history.common.domain.db.SearchResult;
import com.history.common.utility.DBUtils;
import com.history.common.utility.db.SearchQueryTemplate;

public class BaseHelperDAO extends HibernateDaoSupport {
	private static final Logit log = Logit.getInstance(BaseHelperDAO.class);
	protected SearchQueryTemplate searchQueryTemplate;
	
	public <T> SearchResult<T> getSearchResult() {
		return this.find(searchQueryTemplate);
	}

	@SuppressWarnings("unchecked")
	public <T> SearchResult<T> find(final SearchQueryTemplate searchQueryTemplate) {
		final String LOCATION = "find(SearchQueryTemplate searchQueryTemplate)";

	       try {
	           SearchResult<T> result = new SearchResult<T>();

	           if (log.ison())
	               log.debug(LOCATION + " -->>> pagingInfo" + searchQueryTemplate.getPagingInfo());

	           // +++ perform search
	           List<T> listRs = getHibernateTemplate().executeFind(new HibernateCallback() {
	               public Object doInHibernate(Session em) throws HibernateException, SQLException {
	                   Query query = searchQueryTemplate.getQuery(em);
	                   DBUtils.addPaging(query, searchQueryTemplate.getPagingInfo());
	                   return query.list();
	               }
	           });
	      
	           if (listRs != null) {
	               result.addAll(listRs);
	           }

	           // +++ perform count
	           Object objTotal = getHibernateTemplate().execute(new HibernateCallback() {
	               public Object doInHibernate(Session em) throws HibernateException, SQLException {
	            	   Query query = searchQueryTemplate.getCountQuery(em);
	            	   return query.uniqueResult();
	               }
	           });

	           DBUtils.setTotalValue(searchQueryTemplate.getPagingInfo(), objTotal);
	           result.setPagingInfo(searchQueryTemplate.getPagingInfo());

	           if (log.ison())
	               log.debug(LOCATION + ":: END");
	           return result;
	       } catch (RuntimeException re) {
	           log.error(LOCATION, re);
	           throw re;
	       }
	}

	/** getter - setter **/
	public SearchQueryTemplate getSearchQueryTemplate() {
		return searchQueryTemplate;
	}

	public void setSearchQueryTemplate(SearchQueryTemplate searchQueryTemplate) {
		this.searchQueryTemplate = searchQueryTemplate;
	}

}
